// import { Toast } from 'antd-mobile'
import { makeAutoObservable } from 'mobx'
import { getCityList, updateUserInfo } from '../api'
import { Toast } from 'antd-mobile'
import type { UserInfoType } from '@/pages/login/api/interface'
import type { CityListType } from '@/pages/personal/api/interface'
import { stores } from '@/stores'
import type { UpdateUserInfoParamsType } from '../api/interface'
class Store {
    public userInfo: Partial<UserInfoType> = {}
    public provinceList: CityListType[] = []
    public cityMap: Record<string, CityListType[]> = {}
    public cityInfo: string = ''
    constructor() {
        makeAutoObservable(this)
        this.initUserInfo()
        this.fetchCityList()
    }
    initUserInfo() {
        this.userInfo = {
            ...stores.userStore.getUserInfo,
        }
    }
    async fetchCityList() {
        let res = await getCityList()
        if (res.data) {
            let cityObj: Record<string, CityListType[]> = {}
            res.data.forEach((item: CityListType) => {
                cityObj[item.code] = item.children
            })
            this.provinceList = res.data
            this.cityMap = cityObj
            this.cityInfo = this.getNameByCityList()
        }
    }

    getNameByCityList() {
        const { province_code, city_code } = this.userInfo
        let provinceInfo: CityListType | undefined = this.provinceList.find(
            record => record.code === province_code,
        )
        let cityName: string =
            provinceInfo?.children.find(record => record.code === city_code)?.name || ''

        if (provinceInfo?.name && cityName) {
            return provinceInfo?.name + cityName
        } else {
            return ''
        }
    }

    updateData = async (params: UpdateUserInfoParamsType) => {
        await updateUserInfo(params)
        Toast.show('更新成功')
        const newUserInfo = {
            ...stores.userStore.getUserInfo,
            ...params,
        }
        stores.userStore.updateUserInfo(newUserInfo as UserInfoType)
        this.initUserInfo()
        this.cityInfo = this.getNameByCityList()
    }
}

export default Store
